import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/home", '/', '/mobile','/mobile/detail', '/detail']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  // console.log("-00000")
  NProgress.start();
  // set page title
  document.title = getPageTitle(to.meta.title);
  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    // console.log("00000")
    if (to.path === "/login") {
      // console.log("1111", a)
      // if is logged in, redirect to the home page
      next({ path: (to.query && to.query.redirect) || "/" });
      NProgress.done();
    } else {
      // console.log("2222", a)
      // var hasroutes =
      //   store.getters.permission_routes &&
      //   store.getters.permission_routes.length > 0;
      var hasroutes = store.getters.name && store.getters.name != ''
      //   console.log("hasroutes",store.getters.name)
      if (hasroutes) {
        // console.log("3333", a)
        // if (to.matched.length !== 0) {
        //   next()
        // } else {//无页面权限，针对name模式
        //   next({ path: '/404' })
        // }
        next()
      } else {
        // console.log("44444", a)
        try {
					const { roles } = await store.dispatch('user/getInfo')
          console.log("44444roles", roles)
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes"
          );
          // dynamically add accessible routes
          router.addRoutes(accessRoutes);
          // console.log("99999")
          // a = a + 1
          next({ ...to, replace: true });
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
